package Controllers;

import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class MyTableFormat {

    public void formatTable(JTable tbFormat) {
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(0);
        TableCellRenderer myRenderer = tbFormat.getTableHeader().getDefaultRenderer();
        JLabel label1 = (JLabel) myRenderer;
        label1.setHorizontalAlignment(JLabel.CENTER);

        int numCols = tbFormat.getColumnCount();
        TableColumnModel columnModel = tbFormat.getColumnModel();
        for (int column = 0; column < numCols; column++) {
            tbFormat.getColumnModel().getColumn(column).setCellRenderer(renderer);
            int width = 50; // Min width
            int numRows = tbFormat.getRowCount();
            for (int row = 0; row < numRows; row++) {
                Component comp = tbFormat.prepareRenderer(myRenderer, row, column);
                width = Math.max(comp.getPreferredSize().width, width);
            }
            columnModel.getColumn(column).setPreferredWidth(width);
        }
    }

    public void clearTable(JTable tbClear) {
        DefaultTableModel model = (DefaultTableModel) tbClear.getModel();
        int size = model.getRowCount();
        for (int i = size - 1; i >= 0; i--) {
            model.removeRow(i);
        }
    }

    public void resizeFitRows(JTable tbResize) {
        try {
            int numRows = tbResize.getRowCount();
            for (int row = 0; row < numRows; row++) {
                int rowHeight = tbResize.getRowHeight();
                int numCols = tbResize.getColumnCount();
                for (int column = 0; column < numCols; column++) {
                    Component comp = tbResize.prepareRenderer(tbResize.getCellRenderer(row, column), row, column);
                    rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
                }
                tbResize.setRowHeight(row, rowHeight);
            }
        } catch (Exception e) {
        }
    }
}
